import React, { Component } from "react";
import ReactDOM from "react-dom";
import {
  Input,
  Table,
  Button,
  Message,
  Pagination,
  MessageBox,
  Dialog,
} from "element-react";
import BreadCroumb from "../../components/BreadCroumb/BreadCroumb.jsx";
import { getUserList, delUser, editUserRole } from "../../assets/js/http.js";
import "./userList.css";
class userList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: "",
      pageInfo: {
        page: 1,
        pageSize: 10,
        total: 1,
      },
      editForm: {
        id: "",
        role: "",
      },
      breadList: [
        {
          breadName: "SonghanUI",
        },
        {
          breadName: "用户管理",
        },
        {
          breadName: "用户列表",
        },
      ],
      dialogVisible: false,
      columns: [
        {
          label: "序号",
          prop: "",
          render: (text, record, index) => `${index + 1}`,
          width: 70,
        },
        {
          label: "账号",
          prop: "username",
        },
        {
          label: "密码",
          prop: "password",
          render: (row, record, index) => {
            var ary = row.password.split("");
            ary.splice(3, 4, "****");
            var tel1 = ary.join("");
            return <span>{tel1}</span>;
          },
        },
        {
          label: "权限",
          prop: "role",
        },
        {
          label: "电话",
          prop: "phone",
          render: (row) => {
            var ary = row.phone.split("");
            ary.splice(3, 4, "****");
            var tel1 = ary.join("");
            return <span>{tel1}</span>;
          },
        },
        {
          label: "操作",
          prop: "",
          width: 150,
          render: (text, record, index) => {
            return (
              <div>
                <Button
                  type="success"
                  size="small"
                  onClick={this.editUser.bind(this, text)}
                >
                  编辑
                </Button>
                <Button
                  type="danger"
                  onClick={this.removeUser.bind(this, text, record, index)}
                  size="small"
                >
                  删除
                </Button>
              </div>
            );
          },
        },
      ],
      tableData: [],
      search: {
        searchName: "",
      },
    };
  }
  // 修改用户
  async editUser(row) {
    await this.setState({
      editForm: Object.assign({}, this.state.editForm, { id: row._id }),
      dialogVisible: true,
    });
  }
  // 绑定数据
  onChange(value) {
    this.setState({
      search: Object.assign({}, this.state.search, { searchName: value }),
    });
  }
  // 绑定数据
  editChange(value) {
    this.setState({
      editForm: Object.assign({}, this.state.editForm, { role: value }),
    });
  }
  // 删除
  removeUser(row) {
    MessageBox.confirm("此操作将永久删除该用户, 是否继续?", "提示", {
      type: "warning",
    })
      .then(() => {
        this.delUser(row._id);
      })
      .catch(() => {});
  }
  // 修改用户权限
  async editUserRole() {
    let { code, msg } = await editUserRole(this.state.editForm);
    if (code == 1) {
      Message({
        message: "修改成功",
        type: "success",
      });
      this.getUserList();
    } else {
      Message({
        message: msg,
        type: "error",
      });
    }
    this.setState({
      dialogVisible: false,
    });
  }
  // 删除用户
  async delUser(id) {
    let params = {
      id,
    };
    let { code, msg } = await delUser(params);
    if (code == 1) {
      Message({
        message: "删除成功",
        type: "success",
      });
      this.getUserList();
    } else {
      Message({
        message: msg,
        type: "error",
      });
    }
  }
  // pagechange事件
  async pageChange(page) {
    await this.setState({
      pageInfo: Object.assign({}, this.state.pageInfo, { page: page }),
    });
    this.getUserList();
  }
  // 获取用户列表数据
  async getUserList() {
    let params = {
      token: this.state.user[0].token,
      page: this.state.pageInfo.page,
      pageSize: this.state.pageInfo.pageSize,
      searchName: this.state.search.searchName,
    };
    let { code, data, msg } = await getUserList(params);
    if (code == 1) {
      this.setState({
        tableData: data.userList,
      });
      for (let key in this.state.pageInfo) {
        this.setState({
          pageInfo: Object.assign({}, this.state.pageInfo, {
            [key]: data.params[key],
          }),
        });
      }
    } else {
      Message({
        message: msg,
        type: "error",
      });
    }
  }
  // 页面加载前获取数据
  async componentWillMount() {
    let user = JSON.parse(localStorage.getItem("user")) || null;
    if (!user) {
      this.props.history.push("/login");
      Message({
        message: "请先登录",
        type: "warning",
      });
      return;
    } else {
      await this.setState({
        user: user,
      });
    }

    this.getUserList();
  }
  render() {
    return (
      <div className="userList">
        <BreadCroumb breadList={this.state.breadList} />
        <div className="content_title mt-10">
          <div className="title_text">用户列表</div>
        </div>
        <div className="wd-300 mt-10">
          <Input
            placeholder="请输入用户账号搜索"
            value={this.state.search.searchName}
            onChange={this.onChange.bind(this)}
            onBlur={this.getUserList.bind(this)}
          />
        </div>
        <div className="table-box mt-20">
          <Table
            style={{ width: "100%" }}
            columns={this.state.columns}
            data={this.state.tableData}
            border={true}
          />
        </div>
        <div className="dialog">
          <Dialog
            title="修改用户权限"
            size="tiny"
            style={{ width: "30%" }}
            visible={this.state.dialogVisible}
            onCancel={() => this.setState({ dialogVisible: false })}
            lockScroll={false}
          >
            <Dialog.Body>
              <Input
                placeholder="请输入新的用户权限"
                value={this.state.editForm.role}
                onChange={this.editChange.bind(this)}
              />
            </Dialog.Body>
            <Dialog.Footer className="dialog-footer">
              <Button onClick={() => this.setState({ dialogVisible: false })}>
                取消
              </Button>
              <Button type="primary" onClick={() => this.editUserRole()}>
                确定
              </Button>
            </Dialog.Footer>
          </Dialog>
        </div>
        <div className="page mt-20">
          <Pagination
            layout=" pager,  jumper"
            total={this.state.pageInfo.total}
            onCurrentChange={this.pageChange.bind(this)}
            pageSize={this.state.pageInfo.pageSize}
            currentPage={this.state.pageInfo.page}
          />
        </div>
      </div>
    );
  }
}
export default userList;
